package com.rws;

import com.rws.monitoring.ControlMonitor;
import com.rws.monitoring.DateControlMonitor;

import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 构建方式创建锁
 */
public class SubjectReadWriteBuilder {

    private List<Observer> observers = SubjectLocalContext.getObservers();

    /**
     * 对象锁
     */
    private ReadWriteLock readWriteLock;

    /**
     * 锁监听器
     */
    private ControlMonitor monitor;


    public SubjectReadWriteBuilder(){
        this(true);
    }

    public SubjectReadWriteBuilder(boolean isLocalLock){
        if(isLocalLock){
            lock(new ReentrantReadWriteLock());
            monitor = new DateControlMonitor();
        }
    }

    public SubjectReadWriteBuilder lock(ReadWriteLock readWriteLock){
        this.readWriteLock = readWriteLock;
        return this;
    }

    public SubjectReadWriteBuilder monitor(ControlMonitor monitor){
        this.monitor = monitor;
        return this;
    }

    public ReadWriteSubject writeLock(){
        ReadWriteSubject readWriteSubject = new ReadWriteSubject(readWriteLock.writeLock(), observers, monitor);
        return readWriteSubject;
    }

    public ReadWriteSubject readLock(){
        ReadWriteSubject readWriteSubject = new ReadWriteSubject(readWriteLock.readLock(), observers, monitor);
        return readWriteSubject;
    }

}
